package com.example.back.controller;
import com.example.back.common.Result;
import com.example.back.entity.InStore;
import com.example.back.service.InStoreService;
import com.example.back.service.StoreService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/InStore")
public class InStoreController {
    @Resource
    private InStoreService inStoreService;
    @Resource
    private StoreService storeService;
    //新增
    @PostMapping("/add")
    public Result add(@RequestBody InStore inStore) {
        try{
            if (inStoreService.getById(inStore.getInId()) != null){
                return Result.error("货物订单已经存在");
            } else if (storeService.getById(inStore.getInStoreId()) == null){
                return Result.error("仓库不存在");
            } else{
                return Result.success(inStoreService.save(inStore),"入库成功");
            }
        }catch(Exception ex){
            return Result.error("入库失败ERROR，违反主键约束，请输入其他ID");
        }

    }

    //查找所有入库信息
    @GetMapping("/find")
    public Result find() {
        return Result.success(inStoreService.list());

    }



    @PostMapping("/get")
    public Result get(@RequestBody InStore inStore) {
        try{
            List<InStore> inStoreList = new ArrayList<>(5);
            if (inStoreService.getById(inStore.getInId()) != null){
                inStoreList.add(inStoreService.getById(inStore.getInId()));
                return Result.success(inStoreList,"查找成功");
            }
            else {
                return Result.error("查找失败");
            }
        }catch(Exception ex){
            return Result.error("查找失败ERROR");
        }
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody InStore inStore) {
        try{
            if (inStoreService.getById(inStore.getInId()) != null && inStoreService.getById(inStore.getInId()).getRealTon() == 0) {
                return Result.success(inStoreService.removeById(inStore.getInId()),"删除成功");
            }
            else {
                return Result.error("删除失败");
            }

        }catch(Exception ex){
            return Result.error("删除失败ERROR");
        }

    }

    @PostMapping("/modify")
    public Result modify (@RequestBody InStore inStore){
        try{
            if (inStoreService.updateById(inStore)){
                return Result.success(inStoreService.updateById(inStore),"修改成功");
            } else if (storeService.getById(inStore.getInStoreId()) == null) {
                return Result.error("修改失败，没有该仓库");

            }
            else return Result.error("修改失败");
        }catch(Exception ex){
            return Result.error("修改失败ERROR");
        }


    }

}
